<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||	
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws. 
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.). 
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations). 
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Poll/classes/PhpFox_ServicePoll.class.php, $Author:  $ */



class PhpFox_Mod_Poll_ServicePoll extends BaseService
{
    function onDeleteAccount($aParams)
    {
        $oPollItem = &$this->_oModule->getItem('Poll');
        /* @var $oPollItem PhpFox_Mod_Poll_ItemPoll */
        $oAccountService = &App::getModuleService('Account', 'Account');
        /* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */

        $aIds = $aParams['aIds'];
        foreach ($aIds as $iUserId)
        {
            $oUser = $oAccountService->getById($iUserId);
            $sSql = 'SELECT id '.
                   ' FROM '.App::getT('polls').' '.
                   ' WHERE user = "'.$oUser->aData['user'].'"';
            $aPolls = $oPollItem->oDb->getRows($sSql);
            foreach ($aPolls as $aPoll)
            {
                $sSql = 'DELETE FROM '.App::getT('poll_vote').' WHERE id = '.$oUser->aData['id'];
                $oPollItem->oDb->query($sSql);
            }
            $sSql = 'DELETE FROM '.App::getT('polls').' WHERE user = "'.$oUser->aData['user'].'"';
            $oPollItem->oDb->query($sSql);
            $sSql = 'SELECT id '.
                   ' FROM '.App::getT('poll_vote').' '.
                   ' WHERE user = "'.$oUser->aData['user'].'" '.
                   ' GROUP BY id';
            $aPolls = $oPollItem->oDb->getRows($sSql);
            $sSql = 'DELETE FROM '.App::getT('poll_vote').' '.
                   ' WHERE user = "'.$oUser->aData['user'].'"';
            $oPollItem->oDb->query($sSql);
            foreach ($aPolls as $aPoll)
            {
                $this->recountPoll($aPoll['id']);
            }
        }
        return true;
    }

    /** Get any poll by ID or random poll
     * 
     * @return array
     */
    function getRandomPoll()
    {
    	if ( phpfoxCache )
    	{
    		$aPolls = $this->oDatabase->getRow("SELECT po.id AS `id`, po.user AS `user`, po.poll AS `poll`, po.option AS `option`, po.time AS `time`, po.o1 AS `o1`, po.o2 AS `o2`, po.o3 AS `o3`, po.o4 AS `o4`, po.a1 AS `a1`, po.a2 AS `a2`, po.a3 AS `a3`, po.a4 AS `a4`, po.type AS `type` FROM `polls` AS po WHERE po.type = 0 ORDER BY RAND() LIMIT 1");  	
    		return $aPolls;
    	}	
    
        $oPollItem = &$this->_oModule->getItem('Poll');
        /* @var $oPollItem PhpFox_Mod_Poll_ItemPoll */

        $aCond = array();
        $aCond['type'] = '= 0';
        $iCnt = $oPollItem->oDb->getField('SELECT COUNT(*) '.
                                         ' FROM '.App::getT('poll').' AS po '.
                                         ' WHERE '.$oPollItem->_parseCond($aCond, $oPollItem->aFields));
        if (!$iCnt)
        {
            return array(0, 0);
        }
        $iRandFrom = rand(1, $iCnt);
        return $oPollItem->getList($aCond, $iRandFrom, 1);
    }

    function recountPoll($iPollId)
    {
        $oPollItem = &$this->_oModule->getItem('Poll');
        /* @var $oPollItem PhpFox_Mod_Poll_ItemPoll */

        $iPollId = intval($iPollId);
        if (!$oPollItem->load($iPollId))
        {
            return false;
        }
        for ($i = 1; $i <= 4; $i++)
        {
            $sField = 'o'.$i;
            $sFieldValue = $oPollItem->aData[$sField];
            $sSql = 'SELECT COUNT(*) '.
                   ' FROM '.App::getT('poll_vote').' '.
                   ' WHERE id = '.$iPollId.' AND '.
                   '       answer = "'.$sFieldValue.'"';
            $iCount = $oPollItem->oDb->getField($sSql);
            $sCountField = 'a'.$i;
            $oPollItem->aData[$sCountField] = $iCount;
            $oPollItem->update(array($sCountField));
        }
        return true;
    }

    /** Check, that user already voted and returns answer
     * @param integer $iPollId
     * @return mixed
     */
    function isUserCanVote($iPollId)
    {
        $oSecurityService = &App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        if (!$sUser = $oSecurityService->getCurrentUserLogin())
        {
            return false;
        }
        
        if ( phpfoxCache )
        {
        	$iPollId = intval($iPollId);
			$aRow = $this->oDatabase->getRow("SELECT answer FROM ". App::getT('poll_vote') ." WHERE id = '". $iPollId ."' AND user = '". $sUser ."'");
			
        }
        else
        {
        	$oPollItem = &$this->_oModule->getItem('Poll');
        	/* @var $oPollItem PhpFox_Mod_Poll_ItemPoll */        
        
        	$iPollId = intval($iPollId);
        	$aRow = $oPollItem->oDb->getRow('SELECT po.type, pv.answer '.
                                       ' FROM '.App::getT('polls').' AS po '.
                                       ' LEFT JOIN '.App::getT('poll_vote').' AS pv USING (id) '.
                                       ' WHERE po.id = '.$iPollId.' '.
                                       '   AND pv.user = "'.$sUser.'"');

		}
        if ( !isset($aRow['answer']) )
        {
            return false;
        }
        if ($aRow['answer'])
        {
            return $aRow['answer'];
        }
        return false;
    }

    /** Get the list of poll voters
     * @param integer $iPollId poll id
     * @return array
     */
    function getVoters($iPollId)
    {
        $oPollItem = &$this->_oModule->getItem('Poll');
        /* @var $oPollItem PhpFox_Mod_Poll_ItemPoll */

        $iPollId = intval($iPollId);
        $iCnt = $oPollItem->oDb->getField('SELECT COUNT(*) '.
                                         ' FROM '.App::getT('poll_vote').' '.
                                         ' WHERE id = '.$iPollId);
        if (!$iCnt)
        {
            return array(array(), 0);
        }
        $aItems = $oPollItem->oDb->getRows('SELECT user, answer, time '.
                                          ' FROM '.App::getT('poll_vote').' '.
                                          ' WHERE id = '.$iPollId);
        return array($aItems, $iCnt);
    }

    /** Write user vote
     * @param integer $iPollId
     * @param integer $iAnswerId
     * @param string $sUser
     * @return boolean
     */
    function votePoll($iPollId, $iAnswerId, $sUser)
    {
        $oPollItem = &$this->_oModule->getItem('Poll');
        /* @var $oPollItem PhpFox_Mod_Poll_ItemPoll */

        $iAnswerId = intval($iAnswerId);
        $iPollId = intval($iPollId);
        if (($iAnswerId < 1) || ($iAnswerId > 4))
        {
            return false;
        }
        $oPollItem->load($iPollId);
        if ($oPollItem->aData['type'] != 0)
        {
            return false;
        }
        $sKey = 'a'.$iAnswerId;
        $oPollItem->aData[$sKey]++;
        $oPollItem->update(array($sKey));
        $aArr = array
        (
            'id'     => $iPollId,
            'user'   => $sUser,
            'poll'   => $oPollItem->aData['poll'],
            'answer' => $oPollItem->aData['o'.$iAnswerId],
            'time'   => time(),
        );
        $oPollItem->oDb->insert(App::getT('poll_vote'), $aArr);
        return true;
    }

    /** Making array with poll answers with percent key and total answers
     * @param array $aPoll poll row array
     * @return array
     */
    function makePollPercents($aPoll)
    {
        $aAnswers = array();
        $iTotal = 0;
        for ($i = 1; $i <= 4; $i++)
        {
            if ($aPoll['o'.$i])
            {
                $aAnswers[$i] = array
                (
                    'answer' => $aPoll['o'.$i],
                    'votes'  => $aPoll['a'.$i],
                );
                $iTotal += $aPoll['a'.$i];
            }
            else
            {
                break;
            }
        }
        foreach ($aAnswers as $iKey => $aAnswer)
        {
            if ($iTotal)
            {
                $aAnswers[$iKey]['percent'] = 100 * round($aAnswer['votes'] / $iTotal, 2);
            }
            else
            {
                $aAnswers[$iKey]['percent'] = 0;
            }
        }
        return array($aAnswers, $iTotal);
    }

    /** Deleting poll with poll votes
     * @param integer $iPollId poll id
     * @return boolean
     */
    function deletePoll($iPollId)
    {
        $oPollItem = &$this->_oModule->getItem('Poll');
        /* @var $oPollItem PhpFox_Mod_Poll_ItemPoll */
        $oAccountService = &App::getModuleService('Account', 'Account');
        /* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */
        $oSecurityService = &App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */

        if (!$iPollId)
        {
            return false;
        }
        $oPollItem->delete($iPollId);
        $oPollItem->oDb->query('DELETE FROM '.App::getT('poll_vote').' WHERE id = '.$iPollId);
        return true;
    }

    /** Reseting poll (deleting poll votes)
     *
     * @param integer $iPollId poll id
     * @return boolean
     */
    function freePoll($iPollId)
    {
        $oPollItem = &$this->_oModule->getItem('Poll');
        /* @var $oPollItem PhpFox_Mod_Poll_ItemPoll */

        if (!$oPollItem->load($iPollId))
        {
            return false;
        }
        $oPollItem->aData['a1'] = 0;
        $oPollItem->aData['a2'] = 0;
        $oPollItem->aData['a3'] = 0;
        $oPollItem->aData['a4'] = 0;
        $oPollItem->update(array('a1', 'a2', 'a3', 'a4'));
        $oPollItem->oDb->query('DELETE FROM '.App::getT('poll_vote').' WHERE id = '.$iPollId);
        return true;
    }
}
?>